package com.qicheng.wlhyspider.hainan.conroller;

import cn.hutool.http.HttpResponse;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.qicheng.wlhyspider.common.Constants;
import com.qicheng.wlhyspider.common.PageResult;
import com.qicheng.wlhyspider.common.RedisUtils;
import com.qicheng.wlhyspider.hainan.dao.DriverRepository;
import com.qicheng.wlhyspider.hainan.entity.DriverEntity;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

@RestController
@RequestMapping("/hainan/driver")
@Slf4j
public class DriverController {
    private final DriverRepository driverRepository;
    private final RedisUtils redisUtils;


    public DriverController(DriverRepository driverRepository, RedisUtils redisUtils) {
        this.driverRepository = driverRepository;
        this.redisUtils = redisUtils;
    }

    @GetMapping("/save")
    public String save(@RequestParam("page") Integer page, @RequestParam("startDate") String startDate, @RequestParam("endDate") String endDate) {
        return saveAll(page, startDate, endDate);
    }

    private String saveAll(Integer page, String startDate, String endDate) {
        String url = String.format("http://wlhy.mot.gov.cn/hainan/basis/driver/list?page=%s&limit=%s&SendingDateTimeRange=%s+~+%s",
                page, 10000, startDate, endDate);
        HttpResponse httpResponse = HttpUtil.createGet(url)
                .header("x-auth-token",redisUtils.get(Constants.TOKEN)+"")
                .execute();
        if (httpResponse.getStatus() == 200) {
            String body = httpResponse.body();
            PageResult pageResult = JSONObject.parseObject(JSONObject.toJSONString(JSONObject.parse(body)), PageResult.class);
            PageResult.ResultDTO result = pageResult.getResult();
            List<DriverEntity> list = JSONArray.parseArray(JSONArray.toJSONString(result.getRecords()), DriverEntity.class);
            driverRepository.saveAll(list);

            log.info(String.format("驾驶员查询，%s到%s，第%s页，总页数%s",startDate,endDate,page,result.getPages()));
            if (page < result.getPages()) {
                page++;
                return save(page, startDate, endDate);
            }

        }  else if (httpResponse.getStatus() == 203) {
            log.info("登录信息失效");
//            return "返回：登录信息失效";
//            LoginUtils.login();
            return saveAll(page, startDate, endDate);
        } else {
            log.info("查询失败");
            return "返回：查询失败";
        }
        log.info("返回：插入成功");
        return "插入成功";
    }
}
